﻿using Autofac;
using Autofac.Integration.Mvc;
using LuShanTea.Front.Web.App_Start;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace LuShanTea.Front.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            // 启动Log4Net日志记录
            log4net.Config.XmlConfigurator.Configure();

            //过滤器
            FilterConfig.RegisterFilters(GlobalFilters.Filters);

            // 自动截取空格，全角字符转换
            ModelBinders.Binders.Add(typeof(string), new TrimToDBCModelBinder());
            #region  AutoFac自动属性注入
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
            //把当前 程序集中的 Controller 都注册 
            //不要忘了.PropertiesAutowired() 
            // 获取所有相关类库的程序集 
            Assembly[] assemblies = new Assembly[] { Assembly.Load("LuShanTea.Service") };
            builder.RegisterAssemblyTypes(assemblies)
                .Where(type => !type.IsAbstract && typeof(IServiceSupport).IsAssignableFrom(type))     //type2是否实现了type1
                .AsImplementedInterfaces().PropertiesAutowired();

            var container = builder.Build();
            //注册系统级别的 DependencyResolver，这样当 MVC 框架创建 Controller 等对象的时候都 是管 Autofac 要对象。 
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//!!! 
            #endregion
        }
    }
}
